<template>
  <div>
    <h3>分类参数</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区 -->
    <el-card class="box-card">
      <el-alert :closable="false" show-icon title="注意：只允许为第三级分类设置相关参数" type="warning"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的 级联选择框 -->
          <el-cascader
            clearable
            v-model="selectedCateKeys"
            :options="options"
            :props="{ expandTrigger: 'hover', value:'cat_id', label:'cat_name', children:'children' }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            round
            size="small"
            :disabled="isBtnDisable"
            @click="addDialog = true"
          >添加参数</el-button>
          <!-- 动态数据表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 标签栏 -->
              <template slot-scope="scope">
                <!-- 从element网上copy -->
                <el-tag
                  :key="index"
                  v-for="(item,index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(item,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editBtn(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteBtn(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            round
            size="small"
            :disabled="isBtnDisable"
            @click="addDialog = true"
          >添加属性</el-button>
          <!-- 静态数据表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 标签栏 -->
              <template slot-scope="scope">
                <!-- 从element网上copy -->
                <el-tag
                  :key="index"
                  v-for="(item,index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(item,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editBtn(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteBtn(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleChange"
      :visible.sync="addDialog"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addDialogForm"
        :rules="addDialogRules"
        ref="addDialogRef"
        label-width="100px"
      >
        <el-form-item :label="titleChange" prop="attr_name">
          <el-input v-model="addDialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addCheckBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog :title="'添加' + titleChange" :visible.sync="editDialog" width="50%">
      <el-form
        :model="editDialogForm"
        :rules="editDialogRules"
        ref="editDialogRef"
        label-width="100px"
      >
        <el-form-item :label="titleChange" prop="attr_name">
          <el-input v-model="editDialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editCheckBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedCateKeys: [],
      options: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],

      // 添加参数对话框
      addDialog: false,
      addDialogForm: {
        attr_name: ''
      },
      addDialogRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },

      // 修改参数对话框
      editDialog: false,
      editDialogForm: {
        attr_name: '',
        attr_vals: ''
      },
      editDialogRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  // 生命周期函数
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      this.options = res.data
    },
    // 当用户在级联菜单中选择内容改变时触发
    async handleChange() {
      // 如果用户选择不是3级分类
      if (this.selectedCateKeys.length != 3) {
        this.selectedCateKeys = []
        this.onlyTableData = []
        this.manyTableData = []
        return
      }
      // console.log(this.selectedCateKeys);
      // 根据用户选择的分类id和当前所处面板获取对应参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      // console.log(res)
      // 循环遍历attr_vals每一个值，将字符串转变为数组split(' ')中，以空格切开
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

        item.inputVisible = false

        item.inputValue = ''
      })
      // console.log(res)

      // 判断当前请求的数据静态、动态，再赋值给对应数组
      if (this.activeName == 'only') {
        this.onlyTableData = res.data
      } else if (this.activeName == 'many') {
        this.manyTableData = res.data
      }
    },
    // Tab栏点击切换事件
    handleTabClick() {
      // 当tab栏切换时，调用级联选择器中的切换函数，变更动态、静态数据显示
      this.handleChange()
    },

    // 添加参数对话框
    addDialogClose() {
      // 清空对话框
      this.$refs.addDialogRef.resetFields()
    },
    // 添加确认按钮
    addCheckBtn() {
      this.$refs.addDialogRef.validate(async valid => {
        if (!valid) {
          return
        }
        // 发送请求，提交数据，接收响应
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addDialogForm.attr_name, attr_sel: this.activeName }
        )

        if (res.meta.status != 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        // 刷新数据列表
        this.handleChange()
        // 关闭对话框
        this.addDialog = false
      })
    },
    // 修改参数对话框
    async editBtn(row) {
      // console.log(row);
      this.editDialog = true
      // 发起请求，传递当前分类id、当前项目id、当前动静态
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      // console.log(res)

      this.editDialogForm = res.data
    },
    // 修改确认按钮
    editCheckBtn() {
      this.$refs.editDialogRef.validate(async valid => {
        if (!valid) {
          return
        }
        // 发送请求，提交数据，接收响应
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editDialogForm.attr_id}`,
          {
            attr_name: this.editDialogForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.attr_vals
          }
        )

        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        // 刷新数据列表
        this.handleChange()
        // 关闭对话框
        this.editDialog = false
      })
    },

    // 删除参数对话框
    async deleteBtn(row) {
      // 从element中查询 Message Box 使用方法
      // .than  .catch  分别操作成功和失败，都需要用一个形参来接收对应信息
      const result = await this.$confirm(
        '此操作将删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(str => {
          return str
        })
        .catch(str => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
          return str
        })
      if (result != 'confirm') {
        return
      }
      // console.log(row.attr_id);

      // 发送删除请求，接收请求参数，注意路径中的分类id、当前项 ID
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      )
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // 刷新数据列表
      this.handleChange()
    },

    // tag标签展开行
    // 删除标签
    async handleClose(item, row) {
      // 将对应标签从数组截取出去
      row.attr_vals.splice(row.attr_vals.indexOf(item), 1)

      // 发起标签修改请求，提交数据，attr_name、attr_sel都是原始数据不用改变，attr_vals只能接收字符串，所以传递前使用join(' ')转换
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 点击新增标签
    showInput(row) {
      row.inputVisible = true
      // 输入框获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加标签
    async handleInputConfirm(row) {
      // console.log(row)

      // 非空判断
      if (!row.inputValue.trim()) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      // 输入框不为空，则将输入值添加到数组
      row.attr_vals.push(row.inputValue)
      row.inputVisible = false
      row.inputValue = ''

      // 发起标签修改请求，提交数据，attr_name、attr_sel都是原始数据不用改变，attr_vals只能接收字符串，所以传递前使用join(' ')转换
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      // console.log(res)

      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    }
  },
  // 计算数字相关逻辑
  computed: {
    // 所选非3级表单，禁用添加按钮
    isBtnDisable() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取第3级分类的id
    cateId() {
      if (this.selectedCateKeys.length == 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 判别动态参数、静态属性，修改对话框标题名称
    titleChange() {
      if (this.activeName == 'only') {
        return '静态属性'
      } else if (this.activeName == 'many') {
        return '动态参数'
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-col {
  margin: 10px 0;
}
// tag标签展开行样式
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>